package com.wbq.datastructuredemo.activity;

import java.io.File;

import com.wbq.datastructuredemo.R;
import com.wbq.datastructuredemo.domain.UpdateInfo;
import com.wbq.datastructuredemo.engine.DownLoadFileTask;
import com.wbq.datastructuredemo.engine.UpdateInfoService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SplashActivity extends Activity {
	
	private static final String TAG = "SplashActivity";
	private TextView tv_splash_version;
	private LinearLayout ll_splash_main;
	private UpdateInfo info;
	private ProgressDialog pd;
	private String versiontext;
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			//判断服务器版本号和客户端的版本号 是否相同
			if(isNeedUpdate(versiontext)){
				Log.i(TAG, "弹出来升级对话框");
				showUpdataDialog();
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//取消标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);
		this.tv_splash_version=(TextView) super.findViewById(R.id.tv_splash_version);
		this.ll_splash_main = (LinearLayout) super.findViewById(R.id.ll_splash_main);
		this.pd = new ProgressDialog(this);
		//显示水平的进度条
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载...");
		versiontext = this.getVersion();
		//让当前的activity延时两秒钟,当前线程是不能被阻塞的,所以要new 一个线程
		new Thread(){

			@Override
			public void run() {
				super.run();
				try {
					sleep(2000);
					handler.sendEmptyMessage(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}.start();
		
		
		this.tv_splash_version.setText(versiontext);
		//设置动画效果,由完全透明到完全不透明
		AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
		alphaAnimation.setDuration(2000);
		ll_splash_main.startAnimation(alphaAnimation);
		//得到当前的窗体  完成窗体的全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}
	
	/**
	 * 升级的对话框
	 */
	private void showUpdataDialog() {
		AlertDialog.Builder builder = new Builder(SplashActivity.this);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle("升级提醒");
		builder.setMessage(info.getDescription());
		builder.setCancelable(false);//防止用户后退清除这个对话框
		builder.setPositiveButton("确定", new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				Log.i(TAG, "下载apk文件"+info.getApkurl());
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					DownloadFileThreadTask task = new DownloadFileThreadTask(info.getApkurl(),"//sdcard//new.apk");
					pd.show();
					new Thread(task).start();
				}else{
					Toast.makeText(getApplicationContext(), "sd卡不可用", Toast.LENGTH_SHORT).show();
					loadMainUI();
				}
			} 
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				Log.i(TAG, "用户取消进入程序主界面");
				loadMainUI();
			}
		});
		builder.create().show();
	}
	/**
	 * 开启多线程下载
	 * 
	 * @author wbq
	 *
	 */
	private class DownloadFileThreadTask implements Runnable{
		private String path;//服务器路径
		private String filepath;//本地文件路径
		
		public DownloadFileThreadTask(String path, String filepath) {
			this.path = path;
			this.filepath = filepath;
		}

		@Override
		public void run() {
			try {
				File file = DownLoadFileTask.getFile(path, filepath,pd);
				Log.i(TAG, "下载成功");
				pd.dismiss();
				//一下代码报错,Toast不能在线程执行,记住
				//Toast.makeText(getApplicationContext(),"下载文件成功",Toast.LENGTH_SHORT).show();
				install(file);
			} catch (Exception e) {
				e.printStackTrace();
				pd.dismiss();
				loadMainUI();
			}
			
		} 
		
	}
	/**
	 * 
	 * @param versiontext 当前客户端的版本信息
	 * @return 是否需要更新
	 */
	private boolean isNeedUpdate(String versiontext) {
		// TODO Auto-generated method stub
		UpdateInfoService service = new UpdateInfoService(SplashActivity.this);
		try {
			info = service.getUpdateInfo(R.string.updateurl);
			String version = info.getVersion();
			if(version.equals(versiontext)){
				Log.i(TAG, "版本相同,无需升级,进入主界面");
				return false;
			}else{
				Log.i(TAG, "版本不同,需要升级");
				return true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(SplashActivity.this, "获取跟新信息异常", Toast.LENGTH_SHORT).show();
			Log.i(TAG, "获取更新信息异常,进入主界面");
			this.loadMainUI();
			return false;
		}
	}
	/**
	 * 获取当前应用程序的版本号
	 * @return
	 */
	private String getVersion(){
		PackageManager packageManager = getPackageManager();
		try {
			PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "版本号未知";
		}
	}
	/**
	 * 页面跳转
	 */
	private void loadMainUI(){
		Intent intent = new Intent(SplashActivity.this,LoginActivity.class);
		startActivity(intent);
		finish();//把当前的activity从任务栈里面移除
	}
	/**
	 * 安装程序
	 * @param file
	 */
	private void install(File file){
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		//类型apk对应的文件文件类型,在tomcat的web.xml文件中查看,查找apk就可以找到
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		finish();
		startActivity(intent);
	}
}
